package com.csot.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.BiMap;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.csot.model._MappingKit;
import com.csot.service.IndexService;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import net.sf.ehcache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.swing.plaf.ListUI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@EnableScheduling
public class InitCache {

    private static final Logger log = LoggerFactory.getLogger(InitCache.class);

    @Autowired
    CacheManager cacheManager;

    @Autowired
    private DataSource ds;

    @Autowired
    private IndexService indexService;

    @PostConstruct
    public void run() throws Exception {

        // TODO Auto-generated method stub
        EhCachePlugin ep = new EhCachePlugin(cacheManager);
        ep.start();

        ActiveRecordPlugin arp = new ActiveRecordPlugin(ds);
        _MappingKit.mapping(arp);
        DbKit.removeConfig("main");
        arp.setShowSql(true);
        arp.start();

        dictCache();

    }

    @Scheduled(cron = "1 1 * * * ?")
    public void dictCache() {
        System.out.println("-----------------刷新缓存开始-------------");
        List<Record> list = Db.find("select dict_type, dict_value, dict_label from sys_dict_data t ");
        Map<String, BiMap<String, String>> map = new HashMap<>();
        for (Record r : list) {
            if (!map.containsKey(r.getStr("dict_type"))) {
                map.put(r.getStr("dict_type"), new BiMap<String, String>(new HashMap<>()));
            }
            map.get(r.getStr("dict_type")).put(r.getStr("dict_value"), r.getStr("dict_label"));
        }

        map.forEach((k, v) -> {
            CacheKit.put("dict-data", k, v);
        });

        List<Record> deptList = Db.find("SELECT dept_id,dept_name from sys_dept");
        Map<String, String> deptMap = new HashMap<>();
        for (Record r : deptList) {
            BiMap<String, String> ip_city = map.get("ip_city");
            deptMap.put(r.getStr("dept_id"), ip_city.getKey(r.getStr("dept_name")));
        }

        CacheKit.put("dict-data", "user-dept", deptMap);

        Caches.initDept();

        indexService.refresh();

        log.info("dict缓存刷新");
        ThreadUtil.execAsync(() -> {
            this.markMistake();
        });
    }

    public void markMistake() {
        List<Record> recordList = Db.find("select * from t_city_segment where ip_end_i = 0");
        if (CollUtil.isEmpty(recordList)) {
            return;
        }
        List<Integer> list = new ArrayList<>();
        for (Record r : recordList) {
            try {
                r.set("ip_start_i", NetUtil.ipv4ToLong(r.getStr("ip_start")));
                r.set("ip_end_i", NetUtil.ipv4ToLong(r.getStr("ip_end")));
            } catch (Exception e) {
                list.add(r.getInt("id"));
                e.printStackTrace();
            }
        }
        System.out.println(list);
        Db.batchUpdate("t_city_segment", recordList, 500);
    }


}
